﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using Swd05.SH.Bll;

namespace Swd05.SH.Dal
{
	class FileScriptFactory : Interfaces.IScriptFactory
	{
		private string folder = string.Empty;
		private const string Extension = ".csmakro";
		
		public Interfaces.IScriptEngine Create( object context )
		{
			ScriptEngine se = null;
			
			se = new ScriptEngine( context, this.FindById( context.GetType().FullName ) );
			
			return se;
		}
		public void Connect(string folder)
		{
			if( ! folder.EndsWith( @"\" ) )
			{
				folder = String.Concat( folder, @"\" );
			}
			this.folder = folder;
		}

		public void Commit(string id, string stream)
		{
			if( stream.Length == 0 )
			{
				File.Delete( this.ToFullName( id ) );
			}
			else
			{
				using( StreamWriter sw = new StreamWriter( this.ToFullName( id ), false, Encoding.Default ) )
				{
					sw.Write( stream );
				}
			}
			
		}

		public bool Exists(string id)
		{
			return File.Exists( this.ToFullName( id ) );
		}

		public string FindById(string id)
		{
			string script = string.Empty;
			if( File.Exists( this.ToFullName( id ) ) )
			{
				using( StreamReader sr = new StreamReader( this.ToFullName( id ), System.Text.Encoding.Default ) )
				{
					script = sr.ReadToEnd();
				}
			}
			return script;
		}

		public DataTable Load()
		{
			DataSet ds		= null;
			DataTable dt	= null;
			FileInfo fi;
			string [] files;
			
			ds = new DataSet( "ds.scripts" );
			
			dt = ds.Tables.Add( "scripts" );
			dt.Columns.Add( "Id", typeof( string ) );
			dt.Columns.Add( "Script", typeof( string ) );
			dt.Columns.Add( "Datum", typeof( DateTime ) );
			
			files  = Directory.GetFiles( this.Folder, string.Format( "*{0}", FileScriptFactory.Extension ) );
			
			foreach( String s in files )
			{
				fi = new FileInfo( s );
				dt.Rows.Add( new object[3]{ fi.Name, this.Read( fi.FullName ), fi.LastWriteTime } );
			}
			dt.AcceptChanges();
			
			return dt;
		}
		private string ToFullName( string name )
		{
			string fullname = string.Empty;
			
			fullname = string.Format( "{0}{1}{2}", this.Folder, name, FileScriptFactory.Extension );
			
			return fullname;
		}
		private string Read( string file )
		{
			string script = string.Empty;
			using( StreamReader sr = new StreamReader( file, System.Text.Encoding.Default ) )
			{
				script = sr.ReadToEnd();
			}
			return script;
		}
		#region Properties
		private string Folder
		{
			get
			{
				if( this.folder == string.Empty )
				{
					throw new NullReferenceException( "ScriptFactoryFS.Folder cannot be empty!" );
				}
				return this.folder;
			}
		}
		#endregion
	}	
}
